﻿using Bear.Library.Util;
using Bear.Library.WinApi;
using Bear.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Bear.BLL.MapleStory
{
    public class StartGame : ScriptBase
    {

        public override void Run(DataCenter data)
        {
            this.OnShowMessage("等待2秒钟,开始启动游戏...");
            Thread.Sleep(2000);

            ProcessStartInfo startInfo = new ProcessStartInfo(data.Config.GamePath);
            startInfo.WorkingDirectory = Path.GetDirectoryName(data.Config.GamePath);

            this.OnShowMessage("运行游戏,{0}", data.Config.GamePath);
            Process process = Process.Start(startInfo);
            this.OnShowMessage("等待第一个说明框");
            process.WaitForInputIdle();
            this.OnShowMessage("获取说明框");
            var rect = new Bear.Library.WinApi.Rect();

            //获取按钮
            IntPtr button = WinApiHelper.FindWindowEx(process.MainWindowHandle, IntPtr.Zero, null, "게임 실행");

            if (button == IntPtr.Zero)
            {
                this.OnShowMessage("未找到按钮 게임 실행!");
                return;
            }
            this.OnShowMessage("点击说明框的按钮...");
            WinApiHelper.GetWindowRect(button, ref rect);
            //移动点击

            int x = rect.Left + (rect.Right - rect.Left) / 2;
            int y = rect.Top + (rect.Bottom - rect.Top) / 2;

            KeyboardMouseOperator.MouseMove(new Point(x, y));
            Thread.Sleep(200);
            KeyboardMouseOperator.MouseClick(true);
            this.OnShowMessage("等待说明框消失...");
            process.WaitForInputIdle();
            this.OnShowMessage("说明框消失，等待游戏窗体");
            IntPtr handle = IntPtr.Zero;
            int isWindow = 0;
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(5000);
                //重新获取窗口句柄
                handle = WinApiHelper.FindWindow(null, data.Config.GameTitle);

                if (handle != IntPtr.Zero)
                {
                    isWindow = WinApiHelper.IsWindowVisible(handle);
                    if (isWindow == 0)
                    {
                        this.OnShowMessage("窗口打开中,请等待...");
                        continue;
                    }
                    break;
                }
            }

            if (isWindow!=0)
            {
                this.OnShowMessage("游戏窗体出现,移动到左上角...");
                WinApiHelper.SetWindowPos(handle, ApiEnums.HWND_TOP, 0, 0, 800, 600, ApiEnums.SWP_NOSIZE);

                data.Handle = handle;
            }
           
        }
    }
}
